package com.dtm.ui;

import java.util.ArrayList;

import javax.jmdns.ServiceEvent;
import javax.jmdns.ServiceInfo;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.dtm.R;
import com.dtm.adapter.ServerAdapter;
import com.dtm.client.ClientConnectedThread;
import com.dtm.client.thread.OnServerChangeListener;
import com.dtm.client.thread.SearchHostThread;
import com.dtm.server.ServerThread;

public class ActivityHome extends Activity implements OnServerChangeListener, OnItemClickListener {
//	Handler handler = new Handler();
	private ServerAdapter serverAdapter;
	private Button btnSearch;
	private Button btnHost;

	private ListView listServer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
		btnSearch = (Button) findViewById(R.id.btn_search);
		btnHost = (Button) findViewById(R.id.btn_host);
		listServer = (ListView) findViewById(R.id.list_server);
		serverAdapter = new ServerAdapter(getApplicationContext(), -1, new ArrayList<ServiceInfo>());
		listServer.setAdapter(serverAdapter);
		listServer.setOnItemClickListener(this);
		
		btnSearch.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				System.out.println("Search clicked 1");
//				SearchHostThread threadClient = new SearchHostThread(getApplicationContext(), ActivityHome.this, handler);
//				new Thread(threadClient).start();
				System.out.println("Search clicked 2");
			}
		});
		
		btnHost.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
			}
		});
	}

	@Override
	public void onFound(ServiceEvent ev) {
		serverAdapter.add(ev.getInfo());
		serverAdapter.notifyDataSetChanged();
	}

	@Override
	public void onRemove(ServiceEvent ev) {
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		ServiceInfo serviceInfo = serverAdapter.getItem(position);
		String ipAdress = "";
		String tempAdress = serviceInfo.getInet4Addresses()[0].toString();
		int length = serviceInfo.getInet4Addresses()[0].toString().length();
		for (int i = 1; i < length; i++) {
			ipAdress = ipAdress + tempAdress.charAt(i);
		}
//		ClientConnectedThread connectThread = new ClientConnectedThread(ipAdress, serviceInfo.getPort());
//		new Thread(connectThread).start();
//		System.out.println(ipAdress);
//		System.out.println(serviceInfo.getPort());
	}

}
